﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using MessengerAPI;
using Microsoft.TeamFoundation.Collaboration;
using Microsoft.TeamFoundation.Collaboration.Microsoft;

namespace TfsCommunity.Collaboration.MessengerMod
{
    [CollaborationProvider("Windows Live Messenger Mod powered by AIT TeamSystemPro")]
    public class WindowsMessengerMod : MessengerProvider
    {
        #region Fields
        private Messenger _messengerInstance;
        private readonly List<string> _requestedForCreation = new List<string>();
        private UserMappingCollection _mappings;
        #endregion

        #region Properties
        public Messenger MessengerInstance
        {
            get { return _messengerInstance ?? (_messengerInstance = new MessengerClass()); }
        }

        /// <summary>
        /// Gets the user mappings.
        /// </summary>
        /// <value>The user mappings.</value>
        public UserMappingCollection UserMappings
        {
            get
            {
                // Upon first access to the mappings we ensure to laod them
                if (_mappings == null)
                {
                    _mappings = new UserMappingCollection();
                    _mappings.Load();
                }
                return _mappings;
            }
        }
        #endregion

        #region Implementation of IDisposable

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            _messengerInstance = null;
        }

        #endregion

        #region Mapping engine
        /// <summary>
        /// Adds the contact.
        /// </summary>
        /// <param name="contactId">The contact id.</param>
        public override void AddContact(string contactId)
        {
            // If this user was already requested do nothing
            if (_requestedForCreation.Contains(contactId))
                return;
            // If the user is already mapped do nothing but if it is not mapped or ignored handle it.
            var mapping = UserMappings.GetUserMapping(contactId);
            if (mapping == null)
                _requestedForCreation.Add(contactId);

        }

        /// <summary>
        /// Gets the contact.
        /// </summary>
        /// <param name="contactId">The contact id.</param>
        /// <returns>The contact that matches the specified <paramref name="contactId"/>.</returns>
        public override Contact GetContact(string contactId)
        {
            var mapping = UserMappings.GetUserMapping(contactId);
            if (mapping != null)
            {
                IMessengerContact user = null;
                // Do not access Messenger if it is not running
                if (IsMessengerRunning())
                {
                    // We return the contact even though it might be marked as ignored.
                    user = (IMessengerContact)MessengerInstance.GetContact(mapping.MessengerName, MessengerInstance.MyServiceId);
                }
                var messengerContact = NewContact(user);
                return messengerContact;
            }
            return null;
        }

        /// <summary>
        /// Returns supported capabilities of original Windows Messenger Provider
        /// Extended by supporting of AddContact
        /// </summary>
        /// <param name="capability">Requested capability</param>
        /// <returns>Supports a feature: true/false</returns>
        public override bool IsSupportedCapability(CollaborationCapability capability)
        {
            if (capability == CollaborationCapability.AddContact)
            {
                return true;
            }
            return base.IsSupportedCapability(capability);
        }


        /// <summary>
        /// Shows the add edit contact UI.
        /// </summary>
        /// <param name="contactId">The contact id.</param>
        public override void ShowAddEditContactUI(string contactId)
        {
            //// Do not access Windows Messenger if it is not running
            if ((!IsMessengerRunning()))
            {
                MessageBox.Show(Properties.Resources.YouCannotAddUsersAsLongAsMessengerIsNotRunning);
                return;
            }

            // Get Messenger contacts
            var messengerUsersFromCOM = (IMessengerContacts)MessengerInstance.MyContacts;
            IList<IMessengerContact> messengerContactsList = messengerUsersFromCOM.Cast<IMessengerContact>().ToList();

            var messengerUsers = new BindingList<IMessengerContact>(messengerContactsList);
            _requestedForCreation.Sort();
            var tfsUsers = new BindingList<string>(_requestedForCreation);
            var presenter = new UserManagementFormPresenter(messengerUsers, tfsUsers) { SelectedTFSUser = contactId, Mappings = UserMappings };
            var addUserDialog = new UserManagementForm(presenter);
            addUserDialog.ShowDialog();
            UserMappings.Save();
        }

        #endregion

        #region Helper Methods
        public bool IsMessengerRunning()
        {
            if (MessengerInstance.MyStatus != MISTATUS.MISTATUS_OFFLINE 
                && MessengerInstance.MyStatus != MISTATUS.MISTATUS_UNKNOWN
                && MessengerInstance.MyStatus != MISTATUS.MISTATUS_LOCAL_DISCONNECTING_FROM_SERVER)
            {
                return true;
            }
            return false;
        }
        #endregion

    }
}
